<template>
  <div class="orders-container">
    <div class="header-bar">
      <el-button type="primary" icon="el-icon-arrow-left" @click="goBack">返回首页</el-button>
      <h2>我的订单</h2>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="全部订单" name="all"></el-tab-pane>
      <el-tab-pane label="已支付" name="paid"></el-tab-pane>

    </el-tabs>

    <div class="filter-bar">
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="fetchOrders"
      />
      <el-input
          v-model="searchKeyword"
          placeholder="搜索电影名称"
          clearable
          @clear="fetchOrders"
          @keyup.enter="fetchOrders"
          style="width: 200px; margin-left: 10px;"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="fetchOrders" />
        </template>
      </el-input>
    </div>

    <div v-loading="isLoading">
      <div v-if="orders.length === 0" class="empty-orders">
        <el-empty description="暂无相关订单">
          <el-button type="primary" @click="goToHome">去购票</el-button>
        </el-empty>
      </div>

      <div v-else>
        <div class="order-card" v-for="order in orders" :key="order.id">
          <div class="order-header">
            <span class="order-id">订单号: {{ order.id }}</span>
            <el-tag :type="getStatusTagType(order.orderStatus)">{{ getStatusText(order.orderStatus) }}</el-tag>
          </div>

          <div class="order-body">
            <div class="movie-info">
              <div class="movie-details">
                <h3>{{ order.title || '未知电影' }}</h3>
              </div>
            </div>

            <div class="order-details">
              <p>总价: <span class="price">¥{{ (order.price || 0).toFixed(2) }}</span></p>
            </div>
          </div>


        </div>

        <div class="pagination">
          <el-pagination
              background
              layout="prev, pager, next"
              :total="totalOrders"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import dayjs from 'dayjs'

const router = useRouter()

// 状态管理
const activeTab = ref('all')
const dateRange = ref([])
const searchKeyword = ref('')
const orders = ref([])
const isLoading = ref(false)
const currentPage = ref(1)
const totalOrders = ref(0)
const pageSize = ref(10)

// 获取订单列表
const fetchOrders = async () => {
  isLoading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: activeTab.value === 'all' ? null : getStatusValue(activeTab.value),
      startDate: dateRange.value.length > 0 ? dateRange.value[0] : null,
      endDate: dateRange.value.length > 0 ? dateRange.value[1] : null,
      keyword: searchKeyword.value
    }

    const response = await request.get('/api/user/orders', { params })
    if (response.code === 200) {
      orders.value = response.data || []
      totalOrders.value = response.total || 0
    } else {
      ElMessage.error(response.message || '获取订单失败')
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    ElMessage.error('网络错误，获取订单失败')
  } finally {
    isLoading.value = false
  }
}

// 标签切换
const handleTabChange = () => {
  currentPage.value = 1
  fetchOrders()
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 支付订单
const payOrder = (orderId) => {
  ElMessageBox.confirm('确认支付该订单?', '支付确认', {
    confirmButtonText: '确认支付',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.post(`/api/order/pay/${orderId}`)
      if (response.code === 200) {
        ElMessage.success('支付成功')
        fetchOrders()
      } else {
        ElMessage.error(response.message || '支付失败')
      }
    } catch (error) {
      console.error('支付失败:', error)
      ElMessage.error('支付失败')
    }
  }).catch(() => {})
}

// 取消订单
const cancelOrder = (orderId) => {
  ElMessageBox.confirm('确认取消该订单?', '取消确认', {
    confirmButtonText: '确认取消',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.post(`/api/order/cancel/${orderId}`)
      if (response.code === 200) {
        ElMessage.success('订单已取消')
        fetchOrders()
      } else {
        ElMessage.error(response.message || '取消失败')
      }
    } catch (error) {
      console.error('取消失败:', error)
      ElMessage.error('取消失败')
    }
  }).catch(() => {})
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 去购票
const goToHome = () => {
  router.push('/')
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'info'
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch(status) {
    case 0: return '未支付'
    case 1: return '已支付'
    case 2: return '退款'
    default: return '未知状态'
  }
}

// 获取状态数值
const getStatusValue = (tabName) => {
  switch(tabName) {
    case 'unpaid': return 0
    case 'paid': return 1
    case 'refunded': return 2
    default: return null
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.header-bar h2 {
  margin-left: 20px;
  margin-bottom: 0;
}

.filter-bar {
  display: flex;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.order-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.order-id {
  font-weight: bold;
}

.order-body {
  display: flex;
  padding: 15px;
}

.movie-info {
  flex: 1;
}

.movie-details {
  padding-left: 15px;
}

.movie-details h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.order-details {
  width: 150px;
  text-align: right;
  padding-right: 10px;
}

.order-details p {
  margin: 5px 0;
}

.price {
  color: #e54847;
  font-weight: bold;
  font-size: 18px;
}

.order-footer {
  padding: 10px 15px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-orders {
  padding: 40px 0;
  text-align: center;
}
</style>